//
//  GYTypeCollectView.m
//  GYDemo
//
//  Created by Mrzhang on 2018/6/25.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "GYTypeCollectView.h"
#import "Head.h"
#import "GYNewShopTypeViewModel.h"


@implementation HHTypeModel
@end

@interface GYTypeCollectView ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    dispatch_group_t GCDGroup;
    NSInteger selectRow;
    NSInteger selectSec;
    NSInteger viewType;
}
@property (nonatomic,strong) UICollectionView *mCollection;
@property(nonatomic,strong)UIView* displayView;
@property(nonatomic,strong)UIButton* finishiBtn;
@property(nonatomic,strong)NSMutableArray* dataSource;
@property(nonatomic,strong)NSMutableArray* PPData;
@end
@implementation GYTypeCollectView
@synthesize mCollection;
-(NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource=[[NSMutableArray alloc] init];
    }
    return _dataSource;
}
-(NSMutableArray *)PPData
{
    if (!_PPData) {
        _PPData=[[NSMutableArray alloc] init];
    }
    return _PPData;
}
-(void)missAllView
{
    
}

-(UIButton *)finishiBtn
{
    if (!_finishiBtn) {
        _finishiBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        [_finishiBtn setTitle:@"完成" forState:UIControlStateNormal];
        [_finishiBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _finishiBtn.backgroundColor=Main_Color_Red;
        _finishiBtn.titleLabel.font=SYSTEMFONT(15);
        _finishiBtn.x=0;
        _finishiBtn.y=ScreenHeight-WFCGFloatY(50);
        _finishiBtn.width=self.size.width;
        _finishiBtn.height=WFCGFloatY(50);
        @WeakSelf;
        [_finishiBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
            
            NSMutableDictionary* backDic=[[NSMutableDictionary alloc] init];
            if (selectSec>=0)
            {
                NSDictionary* dic=[selfp.dataSource objectAtIndex:selectSec];
                NSArray* arr=[dic objectForKey:@"c"];
                HHTypeModel* model=[arr objectAtIndex:selectRow];
                [backDic setObject:model.id forKey:@"protypeid"];
            }

            
            for (NSInteger i=selfp.dataSource.count-selfp.PPData.count; i<selfp.dataSource.count; i++)
            {
                NSDictionary* dic=[selfp.dataSource objectAtIndex:i];
                HHTypeModel* MainModel=[dic objectForKey:@"p"];
                NSInteger HHsel=[[dic objectForKey:@"select"] integerValue];
                NSArray* hhArr=[dic objectForKey:@"c"];
                if (HHsel>=0)
                {
                    HHTypeModel* ppModel=[hhArr objectAtIndex:HHsel];
                    [backDic setObject:ppModel.name forKey:[NSString stringWithFormat:@"%@",MainModel.id]];
                }
            }
            
            selfp.Handler(backDic);

        }];
    }
    return _finishiBtn;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    self=[super initWithFrame:frame];
    if (self)
    {
        [[InterfaceManager shareInterface].specialInterfaces addObject:@"getProductTypeProperty"];
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        CGFloat size = (frame.size.width -46) / 3;
        
        [flowLayout setItemSize:CGSizeMake(size, WFCGFloatY(30))];//设置cell的尺寸
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];//设置其布局方向
        flowLayout.sectionInset = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f);//设置其边界
        flowLayout.minimumInteritemSpacing = 10;
        flowLayout.minimumLineSpacing = 10;
        //其布局很有意思，当你的cell设置大小后，一行多少个cell，由cell的宽度决定
        
        mCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(13, WFCGFloatY(20), frame.size.width -26, ScreenHeight-WFCGFloatY(70)) collectionViewLayout:flowLayout];
        
        mCollection.dataSource = self;
        mCollection.delegate = self;
        [mCollection setBackgroundColor:[UIColor whiteColor]];
        mCollection.showsVerticalScrollIndicator=NO;
        mCollection.showsHorizontalScrollIndicator=NO;
        //注册Cell，必须要有
        [mCollection registerClass:[NewClassCollectionCell class] forCellWithReuseIdentifier:@"cell"];
        [mCollection registerClass:[NewClassReuseView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
        
        [self addSubview:mCollection];
        [self addSubview:self.finishiBtn];
        selectRow=-1;
        selectSec=-1;
    }
    return self;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSDictionary* dic=[_dataSource objectAtIndex:section];
    NSArray* arr=[dic objectForKey:@"c"];
    if ([[dic objectForKey:@"open"] integerValue]==0) {
        return 0;
    }
    return arr.count;
}

//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return [_dataSource count];
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NewClassCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor=[UIColor whiteColor];
    
    NSDictionary* dic=[_dataSource objectAtIndex:indexPath.section];
    NSArray* arr=[dic objectForKey:@"c"];
    
    HHTypeModel* hhmodel=arr[indexPath.row];
    [cell.nameLB setText:hhmodel.name];
    
    if (viewType==1)
    {
        if (indexPath.section>(_dataSource.count-self.PPData.count-1))
        {
            NSInteger selectI=[[dic objectForKey:@"select"] integerValue];
            if (selectI>=0&&selectI==indexPath.row)
            {
                [cell.nameLB setTextColor:HEXCOLOR(@"#B81A08")];
                cell.nameLB.backgroundColor=HEXCOLOR(@"#FFD7DC");
            }else
            {
                [cell.nameLB setTextColor:Main_Color_Black];
                cell.nameLB.backgroundColor=HEXCOLOR(@"#F6F6F6");
            }
            
        }else
        {
            if (selectRow==indexPath.row&&selectSec==indexPath.section) {
                [cell.nameLB setTextColor:HEXCOLOR(@"#B81A08")];
                cell.nameLB.backgroundColor=HEXCOLOR(@"#FFD7DC");
            }else{
                [cell.nameLB setTextColor:Main_Color_Black];
                cell.nameLB.backgroundColor=HEXCOLOR(@"#F6F6F6");
            }
        }
    }
    
    if (viewType==2)
    {

        NSInteger selectI=[[dic objectForKey:@"select"] integerValue];
        if (selectI>=0&&selectI==indexPath.row)
        {
            [cell.nameLB setTextColor:HEXCOLOR(@"#B81A08")];
            cell.nameLB.backgroundColor=HEXCOLOR(@"#FFD7DC");
        }else
        {
            [cell.nameLB setTextColor:Main_Color_Black];
            cell.nameLB.backgroundColor=HEXCOLOR(@"#F6F6F6");
        }
    }

    
    return cell;
}

//每个section
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        NewClassReuseView *reusableview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        reusableview.backgroundColor=[UIColor whiteColor];

        NSDictionary* dic=_dataSource[indexPath.section];
        HHTypeModel* model=[dic objectForKey:@"p"];
        [reusableview.titleLB setText:model.name];
        if ([[dic objectForKey:@"open"] integerValue]==0)
        {
            reusableview.markIV.image=[UIImage imageNamed:@"choose_mark_down"];
        }else
        {
            reusableview.markIV.image=[UIImage imageNamed:@"choose_mark_up"];
        }

        [reusableview.btn setTag:indexPath.section];
        [reusableview.btn addTarget:self action:@selector(showList:) forControlEvents:UIControlEventTouchUpInside];
        return reusableview;
    }
    
    return nil;
}
-(void)showList:(UIButton*)sender
{
    NSInteger str=[[[_dataSource objectAtIndex:sender.tag] objectForKey:@"open"] integerValue];
    [[_dataSource objectAtIndex:sender.tag] setObject:str==1?@"0":@"1" forKey:@"open"];
    [mCollection reloadData];
}
#pragma mark --UICollectionViewDelegateFlowLayout
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(self.bounds.size.width, WFCGFloatY(43));
}
#pragma mark --UICollectionViewDelegate

//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (viewType==1)
    {
        if (indexPath.section>(_dataSource.count-self.PPData.count-1))
        {
            [[_dataSource objectAtIndex:indexPath.section] setObject:[NSString stringWithFormat:@"%ld",indexPath.row] forKey:@"select"];
            [mCollection reloadData];
        }else
        {
            selectSec=indexPath.section;
            selectRow=indexPath.row;
            
            NSDictionary* dic=[_dataSource objectAtIndex:indexPath.section];
            NSArray* arr=[dic objectForKey:@"c"];
            HHTypeModel* hhmodel=arr[indexPath.row];
            
            [self requestProDuct:hhmodel.id];
            [mCollection reloadData];
        }
    }
    
    if (viewType==2)
    {

        [[_dataSource objectAtIndex:indexPath.section] setObject:[NSString stringWithFormat:@"%ld",indexPath.row] forKey:@"select"];
        [mCollection reloadData];
    }

}
-(void)requestSecondtype:(NSString*)fid viewType:(NSInteger)type
{
    viewType=type;
    if (type==1)
    {
        NSString *interface = @"childTypeList";
        NSMutableDictionary* para=[[NSMutableDictionary alloc] init];
        [para setObject:fid forKey:@"id"];
        [[InterfaceManager shareInterface]requetInterface:interface withParameter:para handler:^(NSDictionary *info, InterfaceStatusModel *infoModel) {
            NSArray *data = infoModel.data;
            if ([data isKindOfClass:[NSArray class]])
            {
                for (NSDictionary *dic in data)
                {
                    NSMutableDictionary* dd=[[NSMutableDictionary alloc] init];
                    HHTypeModel *model = [HHTypeModel yy_modelWithJSON:dic];
                    [dd setObject:model forKey:@"p"];
                    [dd setObject:@"1" forKey:@"open"];
                    [dd setObject:@"-1" forKey:@"select"];
                    [self.dataSource addObject:dd];
                }
                
                GCDGroup = dispatch_group_create();
                for (NSMutableDictionary* dd in _dataSource)
                {
                    HHTypeModel* model=[dd objectForKey:@"p"];
                    
                    dispatch_group_enter(GCDGroup);
                    [self requestThird:model.id index:0];
                }
                
                dispatch_group_notify(GCDGroup, dispatch_get_main_queue(), ^{
                    NSLog(@"groupSemaphore所有请求完毕!!!");
                    [mCollection reloadData];
                });
            }
        }];
    }else
    {
     [self requestProDuct:fid];
    }

}
-(void)requestThird:(NSString*)sid index:(NSInteger)index
{
    NSString *interface = @"childTypeList";
    NSMutableDictionary* para=[[NSMutableDictionary alloc] init];
    [para setObject:sid forKey:@"id"];
    [[InterfaceManager shareInterface]requetInterface:interface withParameter:para handler:^(NSDictionary *info, InterfaceStatusModel *infoModel) {
        NSArray *data = infoModel.data;
        if ([data isKindOfClass:[NSArray class]])
        {
            NSMutableArray* arr=[NSMutableArray new];
            for (NSDictionary *dic in data)
            {
                HHTypeModel *model = [HHTypeModel yy_modelWithJSON:dic];
                [arr addObject:model];
            }
            for (int i=0; i<_dataSource.count; i++)
            {
                HHTypeModel* model=[_dataSource[i] objectForKey:@"p"];
                if ([model.id isEqualToString:sid])
                {
                    [_dataSource[i] setObject:arr forKey:@"c"];
                }
            }
        }
        dispatch_group_leave(GCDGroup);
        
    }];
}
-(void)requestProDuct:(NSString*)pid
{
    NSString *interface = @"getProductTypeProperty";
    NSMutableDictionary* para=[[NSMutableDictionary alloc] init];
    [para setObject:pid forKey:@"id"];
    [[InterfaceManager shareInterface]requetInterface:interface withParameter:para handler:^(NSDictionary *info, InterfaceStatusModel *infoModel) {
        NSArray *data = infoModel.data;
        if ([data isKindOfClass:[NSArray class]])
        {
            if (self.PPData.count!=0) {
                [self.dataSource removeObjectsInArray:_PPData];
            }
            [self.PPData removeAllObjects];
            for (NSDictionary *dic in data)
            {
                NSMutableArray* arr=[NSMutableArray new];
                
                NSMutableDictionary* dd=[[NSMutableDictionary alloc] init];
                HHTypeModel *model = [HHTypeModel yy_modelWithJSON:[dic objectForKey:@"productTypeProperty"]];
                
                [dd setObject:model forKey:@"p"];
                [dd setObject:@"1" forKey:@"open"];
                [dd setObject:@"-1" forKey:@"select"];
                NSArray* llArr=[dic objectForKey:@"list"];
                for (int i=0; i<llArr.count; i++)
                {
                    HHTypeModel* ppmodel=[[HHTypeModel alloc] init];
                    ppmodel.id=[llArr[i] objectForKey:@"id"];
                    ppmodel.name=[llArr[i] objectForKey:@"provalue"];
                    [arr addObject:ppmodel];
                }
                
                [dd setObject:arr forKey:@"c"];
                [self.PPData addObject:dd];
            }
            [self.dataSource addObjectsFromArray:self.PPData];

            [mCollection reloadData];

        }
    }];
}

@end


@implementation NewClassReuseView
@synthesize titleLB,btn,markIV;
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        UIView *point = [[UIView alloc]initWithFrame:CGRectMake(0, frame.size.height / 2 - 3, 6, 6)];
        [point setBackgroundColor:[UIColor lightGrayColor]];
        [WFFunctions WFUIaddbordertoView:point radius:3.0f width:0.001f color:[UIColor lightGrayColor]];
        [point setHidden:YES];
        [self addSubview:point];
        
        titleLB = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, frame.size.width - 50, frame.size.height)];
        [titleLB setFont:[UIFont boldSystemFontOfSize:15]];
        [titleLB setTextColor:Main_Color_Black];
        
        [self addSubview:titleLB];
        
        markIV=[[UIImageView alloc] init];
        markIV.image=[UIImage imageNamed:@"choose_mark_up"];
        markIV.x=self.width-30;
        markIV.width=markIV.image.size.width;
        markIV.height=markIV.image.size.height;
        markIV.y=(self.height-markIV.height)/2;
        [self addSubview:markIV];
        
        btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        [self addSubview:btn];
    }
    return self;
}
-(void)setData:(NSDictionary *)dic
{
    
}
@end

@implementation NewClassCollectionCell
@synthesize imageIV,nameLB,info;
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {

        nameLB = [[UILabel alloc]init];
        [nameLB setTextColor:Main_Color_Black];
        [nameLB setFont:SYSTEMFONT(13)];
        [nameLB setTextAlignment:NSTextAlignmentCenter];
        nameLB.backgroundColor=HEXCOLOR(@"#F6F6F6");
        [self addSubview:nameLB];
        [nameLB setFrame:CGRectMake(0, 0, self.width, self.height)];
        [WFFunctions WFUIaddbordertoView:nameLB radius:5 width:0 color: [UIColor clearColor]];
    }
    return self;
}

@end
